class Server
{
    constructor ()
    {
        this.requestRouterSetTimeOut = null;
    }
    // static intervalHandle = 10;
     static getInstance()
     {
         if(!Server.instance){
             Server.instance = new Server();
         }
         return Server.instance;
     }

    /**
     * 更新到服务器
     * 需要满足两个条件
     *   1)OBJECT.routerPonits[routerId].UpdateStatus ==false
     *   2)OBJECT.routerPonits[routerId].driverId  不为空
     *   加上 第一个起点（后仓）和最后一个点（司机家或者货仓）
     */
    updateRouters(){
        clearTimeout(CONFIG.updateRouterTimer);
        let routerPonts = OBJECT.routerPonits;

        for( let key in routerPonts ) {
            if( routerPonts[key].UpdateStatus === false  && routerPonts[key].driverId  )
            {

                    let updateJson = {};
                    let distanceAndTime = assignRoute.getInstance().calcDistanceAndTimes( key );   //总距离和时间
                    updateJson.weight = assignRoute.getInstance().calcLbs( routerPonts[key].points );
                    updateJson.stops = routerPonts[key].points.length
                    updateJson.hours = distanceAndTime.time;
                    updateJson.distance = distanceAndTime.distance;
                    updateJson.vehicle_id =  routerPonts[key].vehicleId;
                    updateJson.driver_id =  routerPonts[key].driverId;
                    updateJson.schedule = routerPonts[key].schedule;
                    updateJson.routers = routerPonts[key].points;
                    updateJson.title   = OBJECT.routersNameMap[key];
                    updateJson.warehouse = CONFIG.wareHouseCode;
                    updateJson.router_edge_points = OBJECT.routerEdgePoints[key];
                    //添加第一个起点
                    updateJson.start_location = `{"lat":${CONFIG.wareHouseCenter.lat},"lng":${CONFIG.wareHouseCenter.lng}}`;
                    let lastPoints = Driver.getInstance().getLastPoint( key );
                    updateJson.end_location =`{"lat":${lastPoints.lat},"lng":${lastPoints.lng}}`;
                    this.submintToServer(key ,updateJson);
                    OBJECT.routerPonits[key].UpdateStatus = true;

            }
        }

         CONFIG.updateRouterTimer =  setTimeout(()=>{
               this.updateRouters();
            },1000)
    }
    /**
     * 是否超过三个点
     * @param routers
     */
    isOverFourPoints(routers)
    {
        return routers.length >=3;
    }
    /**
     * 把每个点放到对应对变形
     */
    assignPointToPolygon()
    {
            clearTimeout(CONFIG.assignRouterTimer);
            let polygon = OBJECT.routerEdgePoints;
            OBJECT.routerPonits = OBJECT.routerPonits || [];
            for( let routerId in polygon )
            {
                let temp = [];
                OBJECT.routerPonits[routerId]= OBJECT.routerPonits[routerId] || [];
                OBJECT.routerPonits[routerId].points = OBJECT.routerPonits[routerId].points ||[];
                for(let CustID in  OBJECT.customerPositionList)
                {
                    if(Polygon.isInArea({lat:OBJECT.customerPositionList[CustID].lat,lng:OBJECT.customerPositionList[CustID].lng}, polygon[routerId]))
                    {
                        temp.push( OBJECT.customerPositionList[CustID] )
                    }
                }
                if(temp.length >=23 )
                {
                    $.Pro('最大不能超过23个点');
                    colseLoading();
                    return false;
                }
                if( OBJECT.routerPonits[routerId].points == 0 )
                {
                    OBJECT.routerPonits[routerId].points=temp;
                }
                if(  temp.length &&  OBJECT.routerPonits[routerId].points.length && OBJECT.routerPonits[routerId].points.length != temp.length )
                {
                    OBJECT.routerPonits[routerId].points=temp;
                }


            }

    }
    /**
     * 更新数据到服务器
     * @param routerId
     * @param data
     */
    submintToServer( routerId , data){
        let post ={
            id:routerId,
            weight:data.weight,
            stops:data.stops,
            hours:data.hours,
            vehicle_id:data.vehicle_id,
            distance:data.distance,
            routers:JSON.stringify(data.routers),
            schedule:JSON.stringify(data.schedule),
            driver_id:data.driver_id,
            title:data.title,
            warehouse:data.warehouse,
            start_location:data.start_location,
            end_location:data.end_location,
            router_edge_points:JSON.stringify( data.router_edge_points )
        }
        $.ajax({
            type: "POST",
            dataType: "json",
            url: CONFIG.updateRouterUrl ,
            data: post,
            success: function (result) {
                //colseLoading();
            },
            error : function() {
                alert('更新失败  ')
            }
        });
    }

    /**
     * 批量请求Directions Service API
     */
    requestRouter()
    {
        this.requestRouterSetTimeOut = setTimeout(()=>{
             let len = OBJECT.requestRoutePromiseHandle.length;
             if(len)
             {
                 if( OBJECT.requestRoutePromiseHandle[0].locked === false && (typeof OBJECT.requestRoutePromiseHandle[0].points !='undefined'))
                 {
                     OBJECT.requestRoutePromiseHandle[0].locked = true;          //设置当前任务为锁定状态
                     let task = OBJECT.requestRoutePromiseHandle[0];
                     new Promise( function ( resovle , reject) {
                        // console.log(`${value.method}(${task.points},${task.routerId},${task.color},${resovle},${reject})`)
                        // task.method(task.points,task.routerId,task.color,resovle,reject).call(Router.getInstance())
                        Router.getInstance().calculateRoute( task.points , task.routerId , task.color ,resovle , reject );
                     }).then( function (value) {
                         OBJECT.requestRoutePromiseHandle.shift();
                         Server.getInstance().requestRouter();
                     },function (error) {
                         console.log('Route Request Fail:'+error);
                     })
                 }
                 showLoading();
             }else{
                 this.requestRouter();
                 colseLoading();
             }
         },500)
    }



}